package com.nut.spp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nut.spp.baidu.MapUtil;
import com.nut.spp.baidu.RegionResult;
import com.nut.spp.common.Result;
import com.nut.spp.entity.SysRegion;
import com.nut.spp.mapper.SysRegionMapper;
import com.nut.spp.service.SysRegionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class SysRegionServiceImpl implements SysRegionService {

    @Autowired
    private SysRegionMapper regionMapper;

    @Override
    public Result refresh() {

        //先清除表中所有数据

        List<RegionResult.District> list = MapUtil.allRegion();

        generateData(list, 0);

        return Result.ok();
    }

    private void generateData(List<RegionResult.District> districts, Integer pid) {
        if (districts.isEmpty()) {
            return;
        }
        for (RegionResult.District district : districts) {

            SysRegion region = new SysRegion();
            region.setPid(pid);
            region.setName(district.getName());
            region.setCode(Integer.valueOf(district.getCode()));
            region.setType(district.getLevel());
            regionMapper.insert(region);

            if (region.getType() != 3 && district.getDistricts() != null && !district.getDistricts().isEmpty()) {
                generateData(district.getDistricts(), region.getId());
            }
        }
    }

    @Override
    public Result<IPage<SysRegion>> listPage(String name, Integer pageNo, Integer pageSize) {
//        Page<Region> page = new Page<>(pageNo, pageSize);
//        IPage<Region> list = regionMapper.listPage(page, name);
//        return Result.ok(list);

        return Result.ok();
    }

    @Override
    public Result<SysRegion> getById(Serializable id) {
        SysRegion region = regionMapper.selectById(id);
        return Result.ok(region);
    }

    @Override
    public Result add(SysRegion region) {
        regionMapper.insert(region);
        return Result.ok();
    }

    @Override
    public Result updateById(SysRegion region) {
        regionMapper.updateById(region);
        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        for (Integer id : ids) {
            regionMapper.deleteById(id);
        }
        return Result.ok();
    }

    @Override
    public Result<List<SysRegion>> list(Integer pid) {
        List<SysRegion> list = regionMapper.selectByPid(pid);
        return Result.ok(list);
    }

    @Override
    public Result<List<SysRegion>> listByCode(Integer code) {
        List<SysRegion> list = regionMapper.selectByCode(code);
        return Result.ok(list);
    }


}